<template>
  <div>

    <a href="#/order">订单页</a>

    <div>
      <input type="text" v-model="goods_title">
      <button @click="search">搜名字</button>
      <input type="text" v-model="min_price">-
      <input type="text" v-model="max_price">
      <button @click="search">搜价格</button>
      <button @click="order_price">价格↑↓</button>
    </div>
    <div>
      <table border="1">
        <tr>
          <td>名称</td>
          <td>价格</td>
          <td>图片</td>
          <td>购买次数</td>
          <td>评论次数</td>
          <td>操作</td>
        </tr>
        <tr v-for="g in goods" :key="g.id">
          <td>{{g.title}}</td>
          <td>{{g.price}}</td>
          <td><img :src="'http://127.0.0.1:8000/'+g.img" alt=""></td>
          <td>{{g.buy_num}}</td>
          <td>{{g.comment_num}}</td>
          <td>
            <button @click="buy(g.id)">购买</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        uid: localStorage.getItem('uid'),
        min_price: 0,
        max_price: 0,
        goods_title: '',
        goods: [], // 保存所有的商品
        ordering: '1',  // price  排序关键字  1: 升序, 2: 降序
      }
    },
    created() {
      this.get_goods()
    },
    methods: {
      search() {
        this.$router.push({
          path: '/search/', query: {
            goods_title: this.goods_title,
            min_price: this.min_price,
            max_price: this.max_price,
          }
        })
      },
      order_price() {
        if (this.ordering == '1') {
          this.ordering = '2'
        } else {
          this.ordering = '1'
        }
        this.get_goods()
      },
      buy(gid) {
        debugger
        if (this.uid) {
        } else {
          location.href = '#/login/'
          return
        }
        this.axios.post('http://127.0.0.1:8000/order/', {
            user: this.uid,
            goods: gid
          }
        ).then(res => {
          alert(res.data.msg)
        }).catch(err => {
          alert(err)
        })
      },
      get_goods() {
        this.axios.get('http://127.0.0.1:8000/goods/', {
          params: {
            ordering: this.ordering
          }
        }).then(res => {
          console.log(res.data)
          this.goods = res.data.data
        }).catch(err => {
          console.log(err)
        })
      }
    }
  }
</script>

<style>
</style>
